import { computed } from 'vue'
import { useUserStore } from '../store/modules/user'
import { TokenManager } from '../utils/request'

export function useAuth() {
  const userStore = useUserStore()
  
  // 计算属性
  const isLoggedIn = computed(() => userStore.isLoggedIn)
  const userType = computed(() => userStore.userType)
  const userId = computed(() => userStore.currentUserId)
  const token = computed(() => userStore.token)
  
  // 方法
  const login = (accessToken, refreshToken, userType, userId) => {
    userStore.setUser(accessToken, refreshToken, userType, userId)
  }
  
  const logout = () => {
    userStore.logout()
  }
  
  const updateToken = (accessToken, refreshToken) => {
    userStore.updateToken(accessToken, refreshToken)
  }
  
  const checkAuth = () => {
    return userStore.checkTokenValidity()
  }
  
  const syncAuth = () => {
    userStore.syncFromStorage()
  }
  
  // 获取TokenManager的原始方法（用于特殊情况）
  const getAccessToken = () => TokenManager.getAccessToken()
  const getRefreshToken = () => TokenManager.getRefreshToken()
  const getUserType = () => TokenManager.getUserType()
  const getUserInfo = () => TokenManager.getUserInfo()
  
  return {
    // 状态
    isLoggedIn,
    userType,
    userId,
    token,
    
    // 方法
    login,
    logout,
    updateToken,
    checkAuth,
    syncAuth,
    
    // TokenManager方法
    getAccessToken,
    getRefreshToken,
    getUserType,
    getUserInfo
  }
}
